# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: on_premise_worker.py
__author__ = "sanyi"
debug = False
if __name__ == "__main__":
    import ssl

    ssl._DEFAULT_CIPHERS += ":!DES-CBC3-SHA:!TLS_RSA_WITH_3DES_EDE_CBC_SHA:!AES128-SHA:!AES256-SHA:!CAMELLIA128-SHA:!CAMELLIA256-SHA:!SEED-SHA:!ECDHE-RSA-DES-CBC3-SHA:!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-RC4-SHA:!RC4-SHA:!RC4-MD5"
    if not debug:
        import gevent.monkey

        gevent.monkey.patch_all()
        import psycogreen.gevent

        psycogreen.gevent.patch_psycopg()
    from helpers.application import on_premise_init
    from settings_provider.onpremise_settings import default_settings

    on_premise_init(default_settings=default_settings)
import logging

__logger = logging.getLogger("service.worker")


def go_worker(run_state_signal):
    from settings_provider import settings
    import time, os.path, tempfile
    from threading import Thread
    from scanners.wvs.wvs_scan_app import WVSScanningApp
    from server.routers.api import ApiRouter
    from server.application import Application
    from helpers.licensing import get_local_license
    from api.descriptors.worker import data as frontend_api
    from api.descriptors.scan import data as scan_api
    from helpers.exceptions.api_error_handlers import api_error_handlers
    from server.routers.static import StaticRouter
    from helpers.application.utils import (
        adjust_ssl_ca_bundle_path,
        create_system_proxy_callback,
        adjust_version_info,
    )
    from helpers.worker.settings_storage import SettingsStorage
    from helpers.setup_types import ON_PREMISE_WORKER

    settings.set("setup_type", ON_PREMISE_WORKER)
    settings_storage = SettingsStorage(
        os.path.join(settings["base_storage"], "worker.json")
    )
    settings.set("worker_settings_storage", settings_storage)
    adjust_version_info()
    settings.set(
        "storage.scan_state_db",
        settings.get("storage.bxss", default=tempfile.gettempdir()),
    )
    __logger.info("starting backend")
    __logger.info("getting license")
    try:
        get_local_license()
    except Exception as e:
        __logger.error("error reading license %s", e)

    adjust_ssl_ca_bundle_path()
    __logger.info("creating system proxy callback")
    create_system_proxy_callback()
    __logger.info("registering session handlers")
    from server.routers.api.auth import XAuthFactory, ApiScanAuth

    auth_factory = XAuthFactory()
    auth_factory.register_auth_type(ApiScanAuth)
    scanning_app = WVSScanningApp(
        working_directory=settings.get("wvs.temp_dir", default=tempfile.gettempdir()),
        wvs_directory=settings.get(
            "wvs.app_dir",
            default=os.path.normpath(os.getcwd() + os.path.sep + ".." + os.path.sep),
        ),
        scan_storage_directory=settings.get(
            "storage.scans", default=tempfile.gettempdir()
        ),
    )

    def create_http_server():
        __logger.info("creating the http server")
        routers = []
        from api.handlers.worker_frontend.status import WorkerStatus

        front_api_router = ApiRouter(
            frontend_api,
            handler_classes=dict(WorkerStatus=WorkerStatus),
            filter_on_host=False,
            filter_on_schema=False,
        )
        routers.append(front_api_router)
        from api.handlers.scan.scans import ScansApiHandler
        from api.handlers.scan.worker import WorkerApiHandler

        scan_api_router = ApiRouter(
            scan_api,
            dict(ScanApiHandler=ScansApiHandler, WorkerApiHandler=WorkerApiHandler),
            filter_on_host=False,
            filter_on_schema=False,
            extra_args=dict(scanning_app_handler=scanning_app),
            auth_factory=auth_factory,
        )
        routers.append(scan_api_router)
        static_document_root = settings.get("server.static_document_root")
        if static_document_root:
            front_static_route = StaticRouter(
                static_document_root,
                index="worker.html",
                extra_headers={"X-Frame-Options": "SAMEORIGIN"},
            )
            routers.append(front_static_route)
        return Application(routers, error_handlers=api_error_handlers)

    def create_server_instance():
        from gevent import pywsgi

        extra_args = {}
        ssl_certificate = settings.get("server.ssl.certificate")
        ssl_private_key = settings.get("server.ssl.private_key")
        if ssl_certificate:
            if ssl_private_key:
                if os.path.exists(ssl_certificate):
                    if os.path.exists(ssl_private_key):
                        extra_args["keyfile"] = ssl_private_key
                        extra_args["certfile"] = ssl_certificate
                __logger.warning("SSL certificate is set but not present!")
                settings.set("secure_cookie", False)
            __logger.warning("SSL certificate is not set!")
            settings.set("secure_cookie", False)
        application = create_http_server()
        from helpers.pywsgi_extra import WSGIHandlerTcpNoDelay

        listening_on = (settings.get("server.address"), settings.get("server.port"))
        print("listening_on", listening_on)
        return pywsgi.WSGIServer(handler_class=WSGIHandlerTcpNoDelay, **extra_args)

    server_instance = create_server_instance()
    import gevent

    if not debug:
        __logger.info("starting the http server")
        server_thread = Thread(target=server_instance.serve_forever)
        server_thread.start()
    else:
        server_thread = gevent.spawn(server_instance.serve_forever)
        server_thread.start()
    time.sleep(1)
    __logger.info("system init completed.")
    while True:
        if run_state_signal.get("shut_down"):
            break
        time.sleep(1)

    __logger.info("shutting down...")
    __logger.info("shutting server instance")
    try:
        server_instance.close()
    except Exception as er:
        __logger.exception("shutdown failed with %s", er)

    try:
        scanning_app.shutdown()
    except Exception as er:
        __logger.exception("shutdown failed with %s", er)

    __logger.info("bye.")


if __name__ == "__main__":
    from settings_provider import settings

    sgn = dict()

    def signal_handler(_signal, _frame):
        global sgn
        __logger.debug("shutdown signal received:")
        sgn["shut_down"] = True

    import signal

    signal.signal(signal.SIGINT, signal_handler)
    from helpers.single_instance import SingleInstance

    SingleInstance("18B55DE6-9EA8-477B-A207-7C2FEF88E3C0")
    go_worker(sgn)
